package org.redis.cluster.command.info;

import java.util.LinkedHashMap;
import java.util.Map;

import org.redis.cluster.Constants;
import org.redis.cluster.RedisCluster;
import org.redis.cluster.plugin.Plugin;
import org.redis.cluster.scheduler.second.SecondScheduler;
import org.redis.cluster.statistics.TimeoutStatistics;

public class ServerInfoFieldProvider implements InfoFieldProvider,Plugin {
	
	private final static String GROUP="server";
	
	private final static String VERSION=Constants.NAME+"_"+Constants.VERSION;
	
	private final static String OS=System.getProperty("os.name");

	private final static String ARCH_BITS=System.getProperty("os.arch");
	
	private final static int SECOND_PER_DAY=60*60*24;
	
	private RedisCluster redisCluster;
	private int port;
	private String runId;
	
	private volatile long second;
	
	@Override
	public void init(RedisCluster redisCluster) {
		this.redisCluster=redisCluster;
		this.port=initPort();
		this.runId=initRunId();
	}
	
	protected int initPort() {
		return redisCluster.getConfigManager().getServerConfig().getPort();
	}
	
	protected String initRunId() { 
		return redisCluster.getConfigManager().getServerConfig().getId();
	}
	
	@Override
	public void destroy() {
	}
	
	@Override
	public String getGroup() {
		return GROUP;
	}

	@Override
	public Map<String, Object> getFields() {
		Map<String,Object> fields=new LinkedHashMap<String,Object>();
		fields.put("redis_version", getVersion());
		fields.put("os", getOs());
		fields.put("arch_bits", getArchBits());
		fields.put("run_id", getRunId());
		fields.put("tcp_port", getPort());
		fields.put("uptime_in_seconds",getUptimeInSeconds());
		fields.put("uptime_in_days",getUptimeInDays());
		fields.put("connect_timeout", getConnectTimeout());
		fields.put("connect_timeout_in_seconds", getConnectTimeoutInSecond());
		return fields;
	}
	
	protected String getVersion() {
		return VERSION;
	}
	
	protected String getOs() {
		return OS;
	}
	
	protected String getArchBits() {
		return ARCH_BITS;
	}
	
	protected int getPort() {
		return port;
	}
	
	protected String getRunId() {
		return runId;
	}
	
	protected long getUptimeInSeconds() {
		return SecondScheduler.getSecond();
	}
	
	protected long getUptimeInDays() {
		return SecondScheduler.getSecond()/SECOND_PER_DAY;
	}
	
	protected int getConnectTimeout() {
		return TimeoutStatistics.getTotalCount();
	}
	
	protected int getConnectTimeoutInSecond() {
		return TimeoutStatistics.getCurrentCount();
	}
}